package cn.zwy.实战;

import java.util.ArrayList;
import java.util.List;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;

public class ASMProxyClassVisitor extends ClassVisitor {
    
    public static ThreadLocal<Boolean> STATIC_METHOD = new ThreadLocal<>();
    public static ThreadLocal<List<String>> CUR_METHOD_PARAMETER_NAMES = new ThreadLocal<>();

    private Class<?> targetClass;

    public ASMProxyClassVisitor(ClassWriter cw, Class<?> targetClass) {
        super(Opcodes.ASM6, cw);
        this.targetClass = targetClass;
    }

    @Override
    public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
        return super.visitField(access, name, desc, signature, value);
    }

    @Override
    public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
        // TODO Auto-generated method stub
        super.visit(version, access, name + "$Proxy", signature, Type.getInternalName(targetClass), interfaces);
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
        if((access & Opcodes.ACC_STATIC) != 0){
            STATIC_METHOD.set(Boolean.TRUE);
        }else{
            STATIC_METHOD.set(Boolean.FALSE);
        }
        if ("addUser".equals(name)) { // 此处的execute即为需要修改的方法 ，修改方法內容
            MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions);// 先得到原始的方法
            return new ASMProxyMethodVisitor(mv);
        } else if ("<init>".equals(name)) {
            MethodVisitor mv = cv.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);  
            mv.visitCode();  
            mv.visitVarInsn(Opcodes.ALOAD, 0);  
            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(targetClass), "<init>", "()V", false);  
            mv.visitInsn(Opcodes.RETURN);  
            mv.visitMaxs(1, 1);  
            mv.visitEnd();  
            return null;
        }
        return cv.visitMethod(access, name, desc, signature, exceptions);// 先得到原始的方法
    }

}
